package com.example.lib_common.utils

import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment

fun AppCompatActivity.switchFragment(
    fragmentTag: String,
    containerViewId: Int,
    fragmentProvider: (String) -> Fragment?,
    enterAnim: Int? = null,
    exitAnim: Int? = null,
    onFragmentVisible: ((Fragment) -> Unit)? = null
): Fragment? {
    val fragmentManager = supportFragmentManager
    val transaction = fragmentManager.beginTransaction()

    // 设置可选动画
    if (enterAnim != null && exitAnim != null) {
        transaction.setCustomAnimations(enterAnim, exitAnim)
    }

    // 隐藏所有 Fragment
    fragmentManager.fragments.forEach { transaction.hide(it) }

    // 查找或创建 Fragment
    val fragment = fragmentManager.findFragmentByTag(fragmentTag)
        ?: fragmentProvider(fragmentTag)?.also {
            transaction.add(containerViewId, it, fragmentTag)
        }
        ?: return null  // 如果 provider 返回 null，则退出

    // 显示当前 Fragment
    transaction.show(fragment)
    transaction.setPrimaryNavigationFragment(fragment)
    transaction.commitAllowingStateLoss()

    // 懒加载回调
    onFragmentVisible?.invoke(fragment)

    return fragment
}
fun Fragment.switchFragment(
    fragmentTag: String,
    containerViewId: Int,
    fragmentProvider: (String) -> Fragment?,
    enterAnim: Int? = null,
    exitAnim: Int? = null,
    onFragmentVisible: ((Fragment) -> Unit)? = null
): Fragment? {
    val fragmentManager = childFragmentManager
    val transaction = fragmentManager.beginTransaction()

    if (enterAnim != null && exitAnim != null) {
        transaction.setCustomAnimations(enterAnim, exitAnim)
    }

    fragmentManager.fragments.forEach { transaction.hide(it) }

    val fragment = fragmentManager.findFragmentByTag(fragmentTag)
        ?: fragmentProvider(fragmentTag)?.also {
            transaction.add(containerViewId, it, fragmentTag)
        }
        ?: return null

    transaction.show(fragment)
    transaction.setPrimaryNavigationFragment(fragment)
    transaction.commitAllowingStateLoss()

    onFragmentVisible?.invoke(fragment)
    return fragment
}
